import { _decorator, AudioClip, AudioSource, CCFloat, CCInteger, Collider2D, Component, Contact2DType, director, instantiate, Label, Node, Prefab, RichText, UITransform, v2, v3, Vec3 } from 'cc';
import { Until } from './Until';
import { Joystick } from './Joystick';
const { ccclass, property } = _decorator;

@ccclass('head')
export class head extends Component {
    //预制体
    @property(Prefab) foodPrefab: Prefab = null;
    @property(Prefab) bodyPrefab: Prefab = null;
    //变量
    @property(Array(Node)) public bodyList: Node[] = [];//蛇身体数组(包含蛇头)
    @property(Node) headNode: Node = null;
    @property(CCInteger) bodyNum: number = 2;//初始蛇身数量
    @property(Vec3) snakeDir: Vec3;//蛇头的方向
    @property(CCFloat) previousMoveDir: Vec3//保存上一帧的移动方向
    @property(CCInteger) Score: number = 0;
    bodyDistance: number = 50;//蛇身之间的距离
    speed: number = 200;//蛇移动速度
    @property(AudioClip)
    public eatSound:AudioClip=null;
    @property(AudioClip)
    public DieSound:AudioClip=null; 
    //ui
    @property(RichText)
    public txt_Score:RichText=null;
    @property(Node)
    public startPanel:Node=null;
    @property(Node)
    public gameOverPanel:Node=null;
    @property(Joystick)
    public joystick: Joystick = null;//摇杆

    protected onLoad(): void {
        this.bodyList = [];
        this.bodyList.push(this.headNode);
        console.info("一开始"+this.headNode.position);
        for (let i = 1; i <= this.bodyNum; i++) {
            this.getNewBody();
        }
        this.headNode.setPosition(Until.getRandomPos());//随机生成位置
        this.previousMoveDir = this.headNode.position.clone().normalize().negative();
        this.rotateHead(this.headNode.position);
        //this.rotateHead(this.node.position);
        console.info("最后"+this.headNode.position);
        
        //this.node.setPosition(this.randomPos());
    }
    //初始化蛇身和增加蛇身的方法
    getNewBody() {
        let newBody = instantiate(this.bodyPrefab);
        //如果蛇身为1（只有蛇头的时候）
        if (this.bodyList.length === 1) {
            let dir = this.headNode.position.clone().normalize();
            console.info(dir)
            newBody.setPosition(this.headNode.position.clone().subtract(dir.multiplyScalar(this.bodyDistance)));
        }
        else {
            let lastBody = this.bodyList[this.bodyList.length - 1];
            let lastBoBody = this.bodyList[this.bodyList.length - 2];
            let dir = lastBoBody.position.clone().subtract(lastBody.position).normalize();
            newBody.setPosition(lastBody.position.clone().subtract(dir.multiplyScalar(this.bodyDistance)));
            // newBody.getComponent(CircleCollider2D).group=16;
        }
        //将实例化的新蛇身放入canvas画布
        console.info(newBody.position);
        this.node.addChild(newBody);
        //将新蛇身放入数组
        this.bodyList.push(newBody);
        this.changZIndex();

    }
    //旋转蛇头的方法
    rotateHead(pos) {
        var angle = v2(1, 0).signAngle(pos) * 180 / Math.PI;; // 从弧度转换为度
        this.headNode.angle = angle + 90;
    }
    start() {
        if(!director.isPaused()){
            director.pause();
        }
        let collider = this.headNode.getComponent(Collider2D);
        if(collider){
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            console.info("开启碰撞");
        }
        this.schedule(() => {
            this.moveBody();
        }, 0.2);
        instantiate(this.foodPrefab).setParent(this.node.parent);
    }

    update(deltaTime: number) {
        this.snakeDir = this.joystick.dir.normalize();

        if (this.snakeDir.length() == 0) {
            this.snakeDir = this.previousMoveDir.clone().normalize();
        } else {
            this.headNode.angle = this.joystick.calculateAngle() - 90;
            this.previousMoveDir = this.snakeDir;
        }
        let newPos = this.headNode.position.clone().add(this.snakeDir.clone().multiplyScalar(this.speed * deltaTime));
        this.headNode.setPosition(newPos);
    }
    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D) {
        console.info(otherCollider.group);
        // 只在两个碰撞体开始接触时被调用一次
        if(otherCollider.group==4){
            otherCollider.node.removeFromParent();
            this.Score++;
            //右上角得分显示
            this.txt_Score.string="<color=#000000>"+this.Score.toString()+"</color>";
            //产生食物
            let newFood=instantiate(this.foodPrefab);
            this.node.parent.addChild(newFood);
            //更新身体
            this.getNewBody();
            this.node.getComponent(AudioSource).playOneShot(this.eatSound);
            
        }
        if(otherCollider.group==8||otherCollider.group==16){
            this.gameOverPanel.active=true;
            this.gameOverPanel.getChildByName("Label").getComponent(Label).string="得分:"+this.Score.toString();
            this.node.getComponent(AudioSource).playOneShot(this.DieSound);
            director.pause();
        }
    }
    changZIndex(){
        let lastIndex=this.node.children.length-1
        for(let i=0;i<this.bodyList.length;i++){
            this.bodyList[i].setSiblingIndex(lastIndex-i);
        }
    }
    moveBody() {
        let headPos = this.headNode.position;//保存蛇头移动前的位置
        for (let i = this.bodyList.length - 2; i >= 0; i--) {//从后往前开始遍历移动蛇身
            this.bodyList[i + 1].position = this.bodyList[i].position//每一个蛇身都移动到它前面一个节点的位置
        }
        this.bodyList[1].position = headPos;
    }
    startGame(){
        if(director.isPaused()){
            director.resume();
        }
        this.startPanel.active = false;
    }   
    reStartGame(){
        director.resume();
        director.loadScene("JoystickSnake");
        this.gameOverPanel.active = false;
    }

}


